import config from './config';
import regular from './regular.js';
import store from 'store';
import api from '@/common/js/api/';

// 时间戳获取
function getTimeS(argument) {
	var timeS = argument + '';
	timeS = timeS.replace(/[年月]/g, '/').replace(/[日]/, '');
	return new Date().getTime() - new Date(timeS).getTime() - 1000; //有一秒的误差
}

function Mul(arg1, arg2) {
	arg1 = parseFloat(arg1);
	arg2 = parseFloat(arg2);
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length
	} catch (e) {}
	try {
		m += s2.split(".")[1].length
	} catch (e) {}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

export default {
	config,
	//富文本图片处理
	normalRichText(content) {
		let ret = '';
		let keys = '/Public/upload/';
		if (!content) {
			return content;
		}
		// ret = content.replace(/<img/g, '<img style=" width:100% !important" class="rich-img" ');
		ret = content.replace(new RegExp(keys, 'g'), config.http + keys);
		return ret;
	},
	/*获取验证码*/
	getCode(that, type) {
		// 验证码类型(1 注册验证码;2 找回密码;3:验证码登录;4:修改手机号)
		console.log('getCode');
		const common = this;
		let istrue = true;
		if (that.verCode.isDownIng) {
			return false;
		}
		let phone = that.form.mobile || that.mobile;
		istrue = regular.isTel(phone);
		if (!istrue) return false;
		let paramData = {
			mobile: phone,
			type
		}
		that.$api.sms(paramData).then(res => {
			if (res.data.code == config.RESOK) {
				common.downDate(that);
				that.$common.showTip(res.data.msg)
			} else {
				that.$common.showTip(res.data.msg)
			}
		}).catch(err => {

		})
	},
	/*验证码倒计时*/
	downDate(that) {
		let i = that.verCode.i;
		that.verCode.t = setInterval(function() {
			that.verCode.text = i + 'S重新获取';
			if (!that.verCode.isDownIng) {
				that.verCode.isDownIng = true;
			}
			i--;
			if (i == 0) {
				clearInterval(that.verCode.t);
				that.verCode.isDownIng = false;
				that.verCode.text = '获取验证码';
			}
		}, 1000);
	},
	/*秒转分小时*/
	formatSeconds(value) {
		var secondTime = parseInt(value); // 秒
		var minuteTime = 0; // 分
		var hourTime = 0; // 小时
		if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
			//获取分钟，除以60取整数，得到整数分钟
			minuteTime = parseInt(secondTime / 60);
			//获取秒数，秒数取佘，得到整数秒数
			secondTime = parseInt(secondTime % 60);
			//如果分钟大于60，将分钟转换成小时
			if (minuteTime > 60) {
				//获取小时，获取分钟除以60，得到整数小时
				hourTime = parseInt(minuteTime / 60);
				//获取小时后取佘的分，获取分钟除以60取佘的分
				minuteTime = parseInt(minuteTime % 60);
			}
		}

		// var result = "" + parseInt(secondTime) + "秒";
		var result = '';
		if (parseInt(secondTime) != 0) {
			result = "" + parseInt(secondTime) + "秒";
		}

		if (minuteTime > 0) {
			result = "" + parseInt(minuteTime) + "分" + result;
		}
		if (hourTime > 0) {
			result = "" + parseInt(hourTime) + "小时" + result;
		}
		return result;
	},
	//时间戳转日期
	timetrans(date, isAll = false) {
		var date = parseInt(date);
		date = date.toString().length == 13 ? new Date(date) : new Date(date * 1000); //如果date为13位不需要乘1000	
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
		if (isAll) {
			var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
			return Y + M + D + h + m + s;
		} else {
			return Y + M + D;
		}
	},
	// 时间统一函数
	getTimeText(argument) {
		var timeS = argument;
		var todayT = ''; //
		var yestodayT = '';
		var timeCha = getTimeS(timeS);
		timeS += '';
		timeS = timeS.slice(-8);
		todayT = new Date().getHours() * 60 * 60 * 1000 + new Date().getMinutes() * 60 * 1000 + new Date()
			.getSeconds() *
			1000;
		yestodayT = todayT + 24 * 60 * 60 * 1000;
		if (timeCha > yestodayT) {
			return argument.slice(0, 11);
		}
		if (timeCha > todayT && timeCha < yestodayT) {
			return timeS.slice(0, 2) > 12 ? '昨天 下午' + (timeS.slice(0, 2) == 12 ? 12 : timeS.slice(0, 2) - 12) + timeS
				.slice(
					2, 5) : '昨天 上午' + timeS.slice(0, 5);
		}
		if (timeCha < todayT) {
			return timeS.slice(0, 2) >= 12 ? '下午' + (timeS.slice(0, 2) == 12 ? 12 : timeS.slice(0, 2) - 12) + timeS
				.slice(
					2, 5) : '上午' + timeS.slice(0, 5);
		}
	},
	/*
	提示框
	*/
	showTip(title, icon = 'none', duration = config.timeLoad) {
		uni.showToast({
			title,
			icon,
			duration,
			mask: true,
		})
	},
	// #ifdef H5
	h5SetTitle(title) {
		if (document.title == title) {
			return false
		}
		document.title = title || document.title;
	},
	/*
	判断是否微信环境
	*/
	isWechat() {
		let ua = window.navigator.userAgent.toLowerCase();
		return ua.match(/MicroMessenger/i) == 'micromessenger';
	},
	/*复制文字*/
	copyPolicyNo(id) {
		var clipboard = new Clipboard('#' + id);
		clipboard.on('success', function(e) {
			uni.showToast({
				title: '复制成功',
				icon: 'success',
			})
			e.clearSelection();
		});
	},
	// #endif
	//是否生产模式
	isDev() {
		return process.env.NODE_ENV === 'development';
	},
	/*回调处理*/
	callback(callback, data = false) {
		if (callback && typeof callback == 'function') {
			callback(data)
		}
	},

	copy(data) {
		uni.setClipboardData({
			data: '' + data,
			success: function() {
				console.log('success');
			}
		});
	},
	/*返回上一页*/
	goback() {
		let pages = getCurrentPages();
		console.log(pages.length);
		if (pages.length > 1) {
			uni.navigateBack({
				delta: 1
			});
		} else {
			if (store.state.userInfo.role == 0) {
				uni.redirectTo({
					url: '/pages/navbar/user'
				})
			}
			//店长
			if (store.state.userInfo.role == 1) {
				uni.redirectTo({
					url: '/pages/sub/agent'
				})
			}
			//配货员
			if (store.state.userInfo.role == 2) {
				uni.redirectTo({
					url: '/pages/delivery/index'
				})
			}
		}
	},
	makePhoneCall(tel) {
		uni.makePhoneCall({
			phoneNumber: '' + tel
		});
	},

	/*获取ip*/
	getIp(callback) {
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://pv.sohu.com/cityjson?ie=utf-8";
		document.getElementsByTagName('head')[0].appendChild(script);
		script.onload = function() {
			if (callback && typeof callback == 'function') {
				callback(returnCitySN)
			}
		} //js加载完成执行方法
	},
	/*获取版本号*/
	getVersion() {
		let version = uni.getSystemInfoSync()['version'];
		version = version.replace(/\./g, "");
		version = version.length > 3 ? version.substring(0, version.length - 1) : version;
		return version
	},
	//过滤emoji表情
	filterEmoji(emoji) {
		let ranges =
			/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;
		return emoji.replace(ranges, '**');
	},
	//获取当前页面对象
	getCurrentPage() {
		let pages = getCurrentPages(); //获取加载的页面
		let currentPage = pages[pages.length - 1]; //获取当前页面的对象
		return currentPage
	},
	/*
	地区联动初始值
	*/
	recursionAddresDefault(value, list) {
		let res = {
			index: [],
			label: [],
			value,
		}
		value.forEach((item, index) => {
			let data = {}
			if (res.index.length) {
				list = list[res.index[res.index.length - 1]].children;
			}
			data = this.recursionAddresValue(item, list);
			res.index.push(data.index);
			res.label.push(data.label);
		})
		return res;
	},
	recursionAddresValue(id, list) {
		let res = {};
		list.find((item, index) => {
			if (item.value == id) {
				res.label = item.label
				res.index = index;
				console.log(item.label, index);
				return true
			}
		})
		return res;
	},
	/*
	地址联动
	*/
	recursionAddres(list) {
		/*不能有多余的属性，要不然app端会卡顿！！！*/
		if (!list.length) {
			return [{
				label: '暂无数据',
				value: 0,
			}]
		}
		return list.map((item, index) => {
			let res = {
				label: item.name,
				value: item.id,
			}
			if (item.citys || item.districts) {
				res['children'] = item.citys ? this.recursionAddres(item.citys) : this.recursionAddres(item
					.districts)
			}
			return res
		})
	},
	//随机数  
	getRandom(arr, ranNum) {
		let result = [];
		for (let i = 0; i < ranNum; i++) {
			let ran = Math.floor(Math.random() * arr.length);
			result.push(arr.splice(ran, 1)[0]);
		};
		return result;
	},
	navigation(data){
		console.log(data)
		uni.openLocation({
			title:data.name,
			latitude: parseFloat(data.lat),
			longitude:  parseFloat(data.lng),
			success: function () {
				console.log('success');
			},
			fail(err){
				console.log(err);
			},
		});
	},
	//乘法 
	accMul(arg1, arg2) {
		let res = 0;
		var m = 0,
			s1 = arg1.toString(),
			s2 = arg2.toString();
		try {
			m += s1.split(".")[1].length
		} catch (e) {}
		try {
			m += s2.split(".")[1].length
		} catch (e) {}
		res = Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
		if (!/\./.test(res)) {
		    res += '.00'
		}
		return res
	},
	//加法 
	accAdd(arg1, arg2) {
		arg1 = parseFloat(arg1);
		arg2 = parseFloat(arg2);
		var r1, r2, m;
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(100, Math.max(r1, r2));
		return (Mul(arg1, m) + Mul(arg2, m)) / m;
	},
	//减法 
	subtr(arg1, arg2) {
		arg1 = parseFloat(arg1);
		arg2 = parseFloat(arg2);
		var r1, r2, m, n;
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(10, Math.max(r1, r2));
		//动态控制精度长度
		n = (r1 >= r2) ? r1 : r2;
		return ((Mul(arg1, m) - Mul(arg2, m)) / m).toFixed(n);
	},
	//获取日期
	getDate() {
		const oDate = new Date();
		let year = oDate.getFullYear();
		let month = oDate.getMonth() + 1;
		let date = oDate.getDate();
		month = month >= 10 ? month : '0' + month;
		date = date >= 10 ? date : '0' + date;
		return `${year}-${month}-${date}`;
	},
	//获取当前的网络
	getNetworkType() {
		const common = this;
		uni.getNetworkType({
			success: function(res) {
				console.log(JSON.stringify(res, undefined, '/t'));
				let networkType = res.networkType;
				let data = {
					networkType: networkType,
					isConnected: networkType == 'none' ? false : true
				};
				if (networkType == 'none') {
					common.showTip('无法链接网络，请检查wifi或者移动数据网络是否正常！', 'none');
				}
				store.commit('setNetwork', data);
			}
		});
	},
	link(url, isLogin = false) {
		const selt = this;
		if (isLogin && !store.state.userInfo) {
			url = '../login/login';
			const page = selt.getCurrentPage();
			let data = {};
			let options = page.options; //页面参数
			console.log(page.options);
			let loginOptions = '';
			if (options) {
				Object.keys(options).forEach((key, index) => {
					if (key != 'first_leader') {
						loginOptions += `${key}=${options[key]}&`
					}
				})
			}
			data.loginRoute = '/' + page.route;
			if (loginOptions.length) {
				loginOptions = loginOptions.substring(0, loginOptions.length - 1);
				data.loginRoute += `?${loginOptions}`;
			}
			console.log(data)
			store.dispatch('setLoginRoute', data.loginRoute);
		}
		uni.navigateTo({
			url,
		});
	},
	formatSize(that) {
		plus.cache.calculate(function(size) {
			console.log('size', size)
			let sizeCache = parseInt(size);
			if (sizeCache == 0) {
				that.fileSizeString = "0B";
			} else if (sizeCache < 1024) {
				that.fileSizeString = sizeCache + "B";
			} else if (sizeCache < 1048576) {
				that.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";
			} else if (sizeCache < 1073741824) {
				that.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";
			} else {
				that.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";
			}
		});
	},
	clearCache(that) {
		let os = plus.os.name;
		if (os == 'Android') {
			let main = plus.android.runtimeMainActivity();
			let sdRoot = main.getCacheDir();
			let files = plus.android.invoke(sdRoot, "listFiles");
			let len = files.length;
			for (let i = 0; i < len; i++) {
				let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
				plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
					if (entry.isDirectory) {
						entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
							uni.showToast({
								title: '缓存清理完成',
								duration: 2000
							});
							that.formatSize(); // 重新计算缓存  
						}, function(e) {
							console.log(e.message)
						});
					} else {
						entry.remove();
					}
				}, function(e) {
					console.log('文件路径读取失败')
				});
			}
		} else { // ios暂时未找到清理缓存的方法，以下是官方提供的方法，但是无效，会报错  
			plus.cache.clear(function() {
				uni.showToast({
					title: '缓存清理完成',
					duration: 2000
				});
				that.formatSize();
			});
		}
	},
	//下载图片保存到相册
	downSave(picurl) {
		const selt = this;
		// 创建下载任务
		//#ifdef APP-PLUS
		uni.showLoading({
			title: '保存中。。',
			mask: false
		});
		console.log('picurl', picurl)
		let name = picurl.split('/');
		console.log(name)
		let picname = `_downloads/${name[name.length - 1]}`;
		console.log(picname)
		var dtask = plus.downloader.createDownload(picurl, {}, function(d, status) {
			// 下载完成
			if (status == 200) {
				console.log('Download success: ' + d.filename)
				plus.gallery.save(
					picname,
					function() {
						selt.showTip('保存成功', 'success')
					},
					function() {
						selt.showTip('保存失败，请重试', 'none')
					}
				);
				uni.hideLoading();
			} else {
				uni.hideLoading();
				selt.showTip('Download failed: ' + status);
			}
		});
		dtask.start();
		//#endif

	},
	async openMap() {
		const [chooseErr, chooseRes] = await uni.chooseLocation();
		if (chooseRes && chooseRes.errMsg == 'chooseLocation:ok') {
			console.log(chooseRes);
			return new Promise((qres, qrej) => {
				qres(chooseRes)
			})
		} else if (chooseErr.errMsg == 'getLocation:fail auth deny' || chooseErr.errMsg ==
			'chooseLocation:fail auth deny') {
			const [modalErr, modelRes] = await uni.showModal({
				title: '提示',
				content: '你已拒绝允许定位授权，是否要重新开启？',
				cancelText: '取消',
				confirmText: '去授权',
			});
			if (modelRes.confirm) {
				const [openErr, openRes] = await uni.openSetting();
				if (openRes.authSetting['scope.userLocation']) {
					this.openMap();
				} else {
					this.showTip('定位授权失败！', 'none');
				}
			}
		} else if (chooseErr.errMsg == 'chooseLocation:fail cancel') {
			this.showTip('已取消定位！', 'none');
		}
	},

	async getVillages(id = null, isShow = false, isSet = true) {
		if (!id) return;
		const res = await this.$api.villages({
			parent_id: id,
		})
		if (res.data.status == this.$config.RESOK) {
			let list = this.$common.recursionArr(res.data.data);
			if (isSet) {
				this.villagesList = list;
			}
			if (isShow) {
				this.villagesShow = true;
			}
			return new Promise((qres, qrej) => {
				qres(list);
			})
		}
	},

	//腾讯地图高德地图 转百度地图
	qqMapTransBMap(lng, lat) {
		if (lng == null || lng == '' || lat == null || lat == '') {
			return {
				lng,
				lat
			};
		}
		var x_pi = 3.14159265358979324;
		var x = parseFloat(lng);
		var y = parseFloat(lat);
		var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		var lng = (z * Math.cos(theta) + 0.0065).toFixed(5);
		var lat = (z * Math.sin(theta) + 0.006).toFixed(5);
		return {
			lng,
			lat
		}
	},
	// 百度地图转腾讯高德
	bMapTransQQMap(lng, lat) {
		if (lng == null || lng == '' || lat == null || lat == '') {
			return {
				lng,
				lat
			};
		}
		var x_pi = 3.14159265358979324;
		var x = parseFloat(lng) - 0.0065;
		var y = parseFloat(lat) - 0.006;
		var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		var lng = (z * Math.cos(theta)).toFixed(7);
		var lat = (z * Math.sin(theta)).toFixed(7);
		return {
			lng,
			lat
		};
	},
	async openMap() {
		const [chooseErr, chooseRes] = await uni.chooseLocation();
		if (chooseErr) {
			console.log('chooseErr', chooseErr);
		}
		if (chooseRes && chooseRes.errMsg == 'chooseLocation:ok') {
			console.log(chooseRes);
			return new Promise((qres, qrej) => {
				qres(chooseRes)
			})
		} else if (chooseErr.errMsg == 'getLocation:fail auth deny' || chooseErr.errMsg ==
			'chooseLocation:fail auth deny') {
			const [modalErr, modelRes] = await uni.showModal({
				title: '提示',
				content: '你已拒绝允许定位授权，是否要重新开启？',
				cancelText: '取消',
				confirmText: '去授权',
			});
			if (modelRes.confirm) {
				const [openErr, openRes] = await uni.openSetting();
				if (openRes.authSetting['scope.userLocation']) {
					this.openMap();
				} else {
					this.showTip('定位授权失败！', 'none');
				}
			}
		} else if (chooseErr.errMsg == 'chooseLocation:fail cancel') {
			this.showTip('已取消定位！', 'none');
		}
	},
}